import * as React from 'react';

import GlobalStyles from '@mui/material/GlobalStyles';
import InfiniteScroll from 'react-infinite-scroll-component'
import {
    Button,
    IconButton,Slide,
} from "@mui/material";
import {FormControl} from "@mui/material";
import {Box} from "@mui/material";
import {TextField,
    ListItemText,} from "@mui/material";
import {styled} from "@mui/material";
import 'dayjs/locale/ru';

import axios from "axios";
import {useParams} from "react-router-dom";
import CloseIcon from "@mui/icons-material/Close";
import Snackbar from "@mui/material/Snackbar";
import MuiAlert from "@mui/material/Alert";
import {useEffect, useState} from "react";

import SendIcon from '@mui/icons-material/Send';
import ButtonsStart from './ButtonsStart'

import MenuButton from './Button';
import ChangeReport from './ReportDialog';

export const TextFieldResult = styled(TextField)`
  fieldset {
    border-radius: 10px;
    border-color: rgb(0, 184, 9);
    border-width: 1px;
  }
  label.Mui-focused {
    color: rgb(0, 184, 9);
  }
  .MuiOutlinedInput-root {
    &:hover fieldset {
      border-color: black;
    }
    &.Mui-focused fieldset {
      border-color: rgb(0, 184, 9)
    }
  }

,

`;


function createData(id,  doctorName, medOrganization, is_remote, msg, noduleType, user, status, date) {
    return {id: id, doctorName: doctorName, medOrganization: medOrganization, is_remote: is_remote, msg: msg, noduleType: noduleType, user:user, status: status, date: date.toLocaleDateString()};
}
const MyChat = (props) => {
    const [chatData, setChatData] = useState([{is_ai: true, created_at: new Date(), text: "Научный агент приветствует вас!"},
{is_ai: false, created_at: new Date(), text: "Расскажи про свои возможности?"}, {is_ai: true, created_at: new Date(), text: 'В настоящий момент бот недоступен. Будем ждать вашего обращения в техническую поддержку!'}])
    const [message, setMessage] = useState("")
    const [next, setNext] = useState("")
    const [formState, setFormState] = useState("");
    const [close, setClose] = useState(true);
    const [page, setPage] = useState(1);
    const [error, setError] = useState(false);
    const [isOpen, setIsOpen] = useState(false);
    const [rm, setRMessage] = useState("")

    useEffect(() => {
        axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('access')}`;
        axios.get("http://localhost:8000/api/v1/messages?page=1&limit=10").then((response) => {
            setChatData(response.data)
            let i = page + 1
            setPage(i)
        })
    }, [props.url])

    const handleNext = () => {
        axios.get(`http://localhost:8000/api/v1/messages?page=${page}&limit=10`).then((response) => {
            let copy = Object.assign([], chatData);
            for(let item of response.data){
                copy.push(item)
            }
            setChatData(copy)
            let i = page + 1
            setPage(i)
            if(response.data.length < 10){
                setNext(null)
            }
            
        })
    }

    function sendMessage(){
        axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('accessToken')}`;
        const formData = {
            "content":  message, "mode": 1
          }
        axios.post("http://localhost:8000/api/message", formData).then((response) => {
            let copy = Object.assign([], chatData);
            console.log(response.data.message)
            copy.unshift(response.data.message)
            // if(response.data[1] !== null){
            //         copy.unshift(response.data[1])
            // }
            // else{
            //     setError(true)
            //     let tmp = copy[0]
            //     copy[0].text = 'В настоящий момент бот недоступен. Будем ждать вашего обращения в техническую поддержку!'
            //     copy[0].is_ai = true
            // }
            setChatData(copy)
            }
            
        )
    }
    const addReport = (event) => {
        setRMessage(event.text)
        setIsOpen(true)
    }

    useEffect(()=>{
       
    }, [rm])

    

    const handleMessage = (event) => {
        setMessage(event.target.value)
    }
    
    function formStart(parameter){
        setFormState(parameter);
    }
    
    function loadResult(){
        let copy = Object.assign([], chatData);
        let item = {text: 'Ваше обращение успешно отправлено', created_at: Date.now(), is_ai: true}
        copy.unshift(item)
        setChatData(copy)
    }

    useEffect(() => {
        console.log(chatData)
    }, [chatData])
    return (
        <div style={{height:'60%', position: "relative", bottom: 0}}>
        {close && <div id="scrollableDiv"
              style={{
                position: 'absolute', width: "100%", bottom: 80,
                  maxHeight: 300,
                  minHeight: 150,
                  overflow: 'auto',
                  display: 'flex',
                  flexDirection: 'column-reverse',
              }}>
            <InfiniteScroll style={{display: 'flex', flexDirection: "column-reverse" }}
                dataLength={chatData.length}
                next={handleNext} inverse={true}
                hasMore={next != null}
                loader={<h4>Loading...</h4>}
                            scrollableTarget="scrollableDiv"
            >
                <GlobalStyles styles={{
                    h7: {   fontSize: 12, fontFamily: "Montserrat", fontWeight: 'lighter', margin: 0},
                    h2: {   fontSize: 10, fontFamily: "Montserrat", fontWeight: 'lighter', margin: 0},
                    h5: {   fontSize: 15, fontFamily: "Montserrat",fontWeight:'bolder', margin: 0},
                    h3: {   fontSize: 12, fontFamily: "Montserrat", fontWeight:'normal', marginBlock: 0},
                    h4: {   fontSize: 15, fontFamily: "Montserrat", fontWeight:'semi-bold', margin: 0}
                }}/>
                {chatData.map((text, i) => (
                            <Box component={""} sx={{flexDirection: !text.is_ai? 'row-reverse': 'row', p:1, m:1, display: 'flex', alignItems: 'center', gap: '20px'}} >
                                <Box component={""} sx={{}}>
                                </Box>
                                <div   style={{borderRadius: 15, border: 'none', backgroundColor: !text.is_ai? 'rgb(97, 196, 102)':'rgb(0, 118, 6)', minHeight: 45, width: 'auto', maxWidth: '70%', justifyContent: 'space-between', display: 'flex', flexDirection: 'row'}}  >
                                    
                                <ListItemText  primary={<h5 style={{color: !text.is_ai? 'black': 'white', textAlign: 'left'}}>{text.content}</h5>} sx={{ padding: 2, paddingLeft:2}} />
                                <ListItemText  primary={<h2 style={{color: !text.is_ai? 'black': 'white', textAlign: 'left'}}>{new Date(text.timestamp).toLocaleTimeString()}</h2>} sx={{ontColor: !text.is_ai? '#003AD0': 'white', paddingTop: 0.5, marginRight:2}} />
                                <ListItemText  primary={<h2 style={{color: !text.is_ai? 'black': 'white', textAlign: 'left'}}>{new Date(text.timestamp).toLocaleDateString()}</h2>} sx={{ontColor: !text.is_ai? '#003AD0': 'white', paddingTop: 0.5, paddingRight:5}} />

                                </div>
                                {text.is_ai&&<Button onClick={(data=text) => addReport(text)} variant='outlined' sx={{height: 50,  fontWeight: 'bolder', borderRadius: 1, color: "rgb(0, 184, 9)", borderRadius: 10,    textAlign: 'right', borderColor: "rgb(0, 184, 9)", "&:hover" :{borderColor: "rgb(0, 184, 115)"}}}>Добавить отчет</Button>}
                            </Box>
                ))}

            </InfiniteScroll>
            </div>
}
            <div style={{position: 'absolute', width: "100%", bottom: 0, display: 'flex', flexDirection: "column"}}>
            <div style={{paddingBottom: 10, display: 'flex', flexDirection: "column"}}>
                {!close && <IconButton sx={{width: 40, padding: 0, color: 'white'}} onClick={()=> setClose(true)}>
                            <CloseIcon></CloseIcon>
                        </IconButton>
                }
            </div>
            <div style={{display: 'flex', flexDirection: "column", alignItems: 'center', justifyContent: 'center'}}>
                
            {!close && formState === "" && 
                        <ButtonsStart chooseButton={formStart}></ButtonsStart>
            }
            </div>
            </div>
            {
                close && 
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'fixed', top: 500}}>
                    <MenuButton text={"Открыть быстрые действия"} onClick={() => setClose(false)}></MenuButton>
                    </div>
            }
            <Box component={""} sx={{width: '75%', paddingBottom: 3, position: 'fixed', top: 600}} alignItems={'center'} display={'flex'}>
                <FormControl sx={{width: '95%'}}>
                    <TextFieldResult
                        multiline
                        value={message}
                        label={!formState === "tech"?"Начните вводить ообщение": "Введите обращение здесь"}
                        onChange={handleMessage}
                        variant='outlined'
                        inputProps={{
                            style: {
                                height: 100,
                                borderRadius: 3,
                                fontSize: 22, 
                                fontFamily: 'Montserrat', color: 'white', "&:focused":{borderColor: 'black'}
                            }
                        }}
                       InputLabelProps={{sx: {fontSize: "0.9rem", color: 'white', fontFamily: 'Montserrat', marginBottom: 0, marginTop: 0, marginLeft: 0, "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
                        borderColor: "black"
                      },"&.Mui-focused": { borderColor: 'black'}, "&.MuiOutlinedInput-notchedOutline": { fontSize: 10, fontColor: 'white', borderColor: 'black'}}}}

                    />
                </FormControl>
                <Box component={""} sx={{marginLeft:0}}>
                    <Button variant={'text'} sx={{height: 50,  fontWeight: 'bolder', borderRadius: 1, color: "rgb(0, 184, 9)",    textAlign: 'right', paddingTop: 1}} onClick={sendMessage}>
                        <SendIcon sx={{paddingRight: 1}}/>   Отправить
                    </Button>
                </Box>
            </Box>
            <ChangeReport open={isOpen} setOpenChangeDialog={setIsOpen} report={null} m={rm}></ChangeReport>
        </div>
    )

}



const ChatPageInterface = (props) => {
    const {number} = useParams();
    return (

        <ChatPage props={number} url={props.url}></ChatPage>

    )
}

const Alert = React.forwardRef(function Alert(props, ref) {
    return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});


class ChatPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            massage: "",
            mode: true,
            info: {},
            open: false,
            author: 0,
            sent: true
        };

    }

    handleClose = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }
        this.setState({
            openSuccess: false,
        })
    };

    handleOpen = () => {
        this.setState({
            open: !this.state.open,
        });
    };

    render() {
        return (
            <div style={{height: "100vh", width: '70%', paddingLeft: "200px"}}>
                <Snackbar  open={this.state.openSuccess} autoHideDuration={6000} onClose={this.handleClose}
                           TransitionComponent={Slide}
                           action={
                               <IconButton
                                   aria-label="close"
                                   color="inherit"
                                   onClick={this.handleClose}
                               >
                                   <CloseIcon/>
                               </IconButton>}>
                    <Alert severity="success" sx={{width:'100%',backgroundColor: '#00d995'}} onClose={this.handleClose}>Результат сохранен!</Alert>
                </Snackbar>
                <div style={{
                    paddingLeft: 95,
                    paddingTop: 10,
                    paddingBottom: 10,
                    borderTopLeftRadius: 130,
                    height: '100%',
                    width: 'auto',
                    minWidth: 500,
                    position: "relative",
                }}>
                    <GlobalStyles styles={

                        {  h1: {color: 'dimgray', fontSize: 25, fontFamily: "Roboto", marginBlock: 0, fontWeight: 'normal'}, h2: {color: 'dimgray', fontSize: 20, fontFamily: "Roboto", whiteSpace:'normal', marginBlockStart: 0,
                                marginBlockEnd:0,
                                marginInlineEnd:5}, h5: {color: 'dimgray', fontSize: 20, fontFamily: "Roboto", fontWeight:'lighter', whiteSpace:'normal', marginBlockStart: 0,
                                marginBlockEnd:0,}}}/>

                    <MyChat url={this.props.url} number={this.props.props} reload={this.state.sent} is_expert={this.state.is_expert}/>
                </div>
            </div>
        )

    }
}

export default ChatPageInterface;